<template>
  <a-card :loading="cardLoading" :bordered="false" >
    <a-spin :spinning="loading">
      <div  class="down-tree" :style={height:vdaH}>
        <a-tree
          :showLine="showLine"
          checkStrictly
          :expandedKeys.sync="expandedKeys"
          :selectedKeys="selectedKeys"
          :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
          :treeData="treeDataSource"
          @select="handleTreeSelect"
          @expand="onExpand"
        />
      </div>
    </a-spin>
  </a-card>
</template>

<script>
import { queryDepartTreeList,queryUserByDepId } from '@/api/api'
import { getAction } from '@api/manage'
export default {
  name: "staffTree.vue",
  props: ['value'],
  data() {
    return {
      vdaH: '0px',
      showLine: true,
      cardLoading: true,
      loading: false,
      treeDataSource: [],
      selectedKeys: [],
      expandedKeys: []
    }
  },
  created() {
    this.queryTreeData()
  },
  methods:{
    queryTreeData(keyword){
      this.commonRequestThen(getAction("/common/staffTree/queryEducationTreeList",{
        departName: keyword ? keyword : undefined
      }))
    },
    handleTreeSelect(selectedKeys, event) {
      console.log(selectedKeys)
      console.log(event)
      if (selectedKeys.length > 0 && this.selectedKeys[0] !== selectedKeys[0]) {
        this.selectedKeys = [selectedKeys[0]]

        if(!event.node.isLeaf){
          let orgCode = event.node.dataRef.orgCode
          this.emitInput({isLeaf:false, id:orgCode})

          if(event.node.dataRef.orgType == '1'){
            return;
          }
          if(event.node.dataRef.children.length==0){
            this.loadLeaves(selectedKeys, event)
          }
        } else {
          let userName = event.node.dataRef.username
          let orgCode = event.node.dataRef.orgCode;
          this.emitInput({isLeaf:true, id:userName,orgCode:orgCode})
        }
      }
    },
    loadLeaves(selectedKeys, event){
      this.loading = true;
      this.cardLoading = true;

      queryUserByDepId({id: selectedKeys[0]}).then(res => {
        if (res.success) {
          res.result.forEach((item, index) => {
            item.isLeaf = true
            item.key = item.username
            item.title = item.realname
            item.orgCode = selectedKeys[0]
          })
          event.node.dataRef.children = res.result
          this.expandedKeys.push(selectedKeys[0])

        } else {
          this.$message.warn(res.message)
          console.error('查询用户失败:', res)
        }
      }).finally(() => {
        this.loading = false
        this.cardLoading = false
      })
    },
    onExpand(expandedKeys, event){
      if(event.expanded==true){
        if(event.node.dataRef.children.length==0){
          this.loadLeaves([expandedKeys[expandedKeys.length-1]], event)
        }
      }
    },
    commonRequestThen(promise) {
      this.loading = true
      promise.then(res => {
        if (res.success) {
          this.treeDataSource = res.result
          console.log(res.result)
          // update-begin- --- author:wangshuai ------ date:20200102 ---- for:去除默认选中第一条数据、默认展开所有第一级
          // 默认选中第一条数据、默认展开所有第一级
          if (res.result.length > 0) {
            this.expandedKeys = []
            res.result.forEach((item, index) => {
              console.log(item)
              if (item.orgType == '0') {
                this.selectedKeys = [item.id]
                // this.emitInput(item.orgCode)

                item.children.forEach((childrenItem, index) => {
                  childrenItem.children = [];
                  childrenItem.isLeaf = false;
                })
              }
              this.expandedKeys.push(item.id)
            })
          }
          // update-end- --- author:wangshuai ------ date:20200102 ---- for:去除默认选中第一条数据、默认展开所有第一级
        } else {
          this.$message.warn(res.message)
          console.error('组织机构查询失败:', res)
        }
      }).finally(() => {
        this.loading = false
        this.cardLoading = false
      })
    },

    emitInput(selectedObj) {
      console.log(selectedObj)
      this.$emit('selectedNode', selectedObj)
    },
  },
  mounted() {
    let h = document.documentElement.clientHeight || document.body.clientHeight;
    this.vdaH = h - 265 + 'px';
    window.onresize = () => {
      return (() => {
        let h = document.documentElement.clientHeight || document.body.clientHeight;
        this.vdaH = h - 265 + 'px';
        console.log(this.vdaH)
      })()
    };
  }

}
</script>

<style scoped>
.down-tree{

  display: block;

  overflow-y: scroll;

}
</style>